
package hash;

import interfaces.IItem;
import interfaces.ITransaction;
import common.Match;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


public class TableItem {
    public IItem item;
    public int occurences;
    public Map<IItem, TableItem> next;
    
    public TableItem(IItem item){
        this.item = item;
        this.occurences = 1;
        this.next = new HashMap<IItem, TableItem>();
    }
    
    public TableItem(List<IItem> items, int itemIndex, TransactionItems ti){
        this.item = items.get(itemIndex);
        this.next = new HashMap<IItem, TableItem>();
        this.occurences = 1; 
        ti.add(this);
        
        if ((itemIndex+1)<items.size()){
            TableItem nextItem = new TableItem(items,itemIndex+1,ti);
            this.next.put(items.get(itemIndex+1), nextItem);
        }
    }
    
    public void addChain(List<IItem> items, int itemIndex, TransactionItems ti){
        ++this.occurences;
        ti.add(this);
        if ((itemIndex+1) < items.size()){
            IItem n = items.get(itemIndex+1);
            TableItem nextItem = next.get(n);
            
            if (null!=nextItem){
                nextItem.addChain(items, itemIndex+1,ti);
            }
            else{
                nextItem = new TableItem(items,itemIndex+1,ti);
                this.next.put(items.get(itemIndex+1), nextItem);
            }
        }
    }
    
    public void getMatches(List<Match> matches, int minSupport, ITransaction prefix){
        if (this.occurences>=minSupport){
            prefix.add(this.item);
            matches.add(new Match(prefix.deepcopy(),this.occurences));
            
            Iterator<TableItem> it = next.values().iterator();
            while (it.hasNext()){
                it.next().getMatches(matches, minSupport, prefix.deepcopy());
            }
        }
    }
    
}
